
  var stompClient = null;
  var STOMP_EXCHANGE_TO_SERVER = "/exchange/magicboxSrv.exchange/srv.magicbox";    // 仅向服务器发送消息
  var MSG_HEAD = "WRJW005C%sFFFFCAM00000CAM00000ComdNAT     ";
  //var serverHost = "192.168.0.138";
  //var serverHost = "192.168.0.105";
  //var serverHost = "115.204.167.30";
  var serverHost = "122.228.136.174";

  function connect(exchange, username, thirdPartyTypeId){

      var headers = {
    		  isConnected: false,
/*/
    		  uri:'http://' + serverHost + ':8899/MagicBox/magicboxSEP',
    	      login: username,
    	      passcode: '123456',
//*/
    	      //uri:'tcp://192.168.0.105:61613',
//*
    	      uri:'tcp://' + serverHost + ':61613',
    	      login: 'guest',
    	      passcode: 'guest',
//*/    	      
    	      'heart-beat': '60000,60000',
    	      // additional header
    	      'thirdPartyTypeId': 'NATTEST'
        };
    
      
      if(thirdPartyTypeId != null){
    	  headers.thirdPartyTypeId = thirdPartyTypeId;
      }
/*
      //===========  stomp.js begin===================== 
      var socket = new SockJS('http://' + serverHost + ':8899/MagicBox/magicboxSEP');

      stompClient = Stomp.over(socket);

      stompClient.connect(headers, function(frame) {
		  setConnected(true);
          console.log('Connected: ' + frame);
          stompClient.subscribe(exchange + 'app.' + username, function(message){
        	  dealwithMsg(message.body);
          });
      });
      //===========  stomp.js end=====================
//*/
      //===========  stomp.java begin=====================
      stompClient = new cordova.plugins.wsstomp.WSStomp({headers: headers});

      stompClient.on('connected', function(frame) {
		  setConnected(true);
          console.log('Connected: ' + JSON.stringify(frame));
          stompClient.subscribe(exchange + 'app.' + username);
          //stompClient.subscribe('app.' + username);
      });
      stompClient.on('subscribed', function(frame) {
    	  console.log('subscribed: ' + JSON.stringify(frame));
          var t=setTimeout(getUserList,1000);
      });
      stompClient.on('disconnect', function(frame) {
    	  setConnected(false);
      });
      stompClient.on('onMessage', function(message) {
    	  console.log('onMessage: ' + JSON.stringify(message));
       	  dealwithMsg(message);
      });
      
      //stompClient.wsConnect(); // websocket连接
      stompClient.connect();     // tcp 连接
     //===========  stomp.java end=====================
//*/      
      return stompClient;
  }
  function getUserList(){
	  sendMsg("&play=users");
  }
  function sendMsg(appendMsg){
	  var _20space = "                    "; // 20 个空白
      var src = _20space;
      src = _20space.substring(0, _20space.length - (username).length) + username;

	  var msgHeader = MSG_HEAD.replace("%s", src);
	  var data = msgHeader + appendMsg;
	  console.log('>>>SEND');
	  console.log('destination:' + STOMP_EXCHANGE_TO_SERVER);
	  console.log('data:\n' + data);
	  stompClient.send(STOMP_EXCHANGE_TO_SERVER, {}, data);
   }
  
  function disconnect(){
      stompClient.disconnect();
	  setConnected(false);
  }

function setConnected(connected) {
    document.getElementById('connect').disabled = connected;
    document.getElementById('disconnect').disabled = !connected;
    if(!connected){
	    if(name === callingTo){
	        if(session != null){
	            session.close();
	        }
	        $('.app').show();
	        $('.chat').hide();
	        $('#answer').show();
	        $('#hangup').hide();
	    }
	    $('ul').html('');
    }
}

function sendData(exchange, routKey){
	var data = $("#message").val();
	stompClient.send(exchange + routKey, {}, data);
	
}

function getQueryStringArgs(dataStr) {
	var args = {};
	var items = dataStr.split("&");
	var item = null, name = null, value = null;
	for (var i = 0; i < items.length; i++) {
		item = items[i].split("=");
		name = decodeURIComponent(item[0]);
		value = decodeURIComponent(item[1]);
		args[name] = value;
	}
	return args;
}

function Trim(str,is_global)
{
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g,"");
    if(is_global)
    {
        result = result.replace(/\s/g,"");
     }
    return result;
}

function dealwithMsg(msg) {
	var cmdStr = Trim(msg, false);;

	if(cmdStr.length < 32){
		
	}else{
		var length = cmdStr.substr(4, 4);
		var src = cmdStr.substr(8, 20);
		var invokeId = cmdStr.substr(28, 4);
		var moduleId = cmdStr.substr(32, 4);
		var mIndexId = cmdStr.substr(36, 4);
		var funcId = cmdStr.substr(40, 4);
		var fIndexId = cmdStr.substr(44, 4);
		var cmd = cmdStr.substr(48, 4);
		var subCmd = cmdStr.substr(52, 4);
		if(cmdStr.length > 56){
			var data = cmdStr.substr(60);
		}
		if(cmd == "Rspn" && subCmd != "0000"){
			data = subCmd + data;
			subCmd = "消息错误";
		}else if(cmd == "Comd" && subCmd == "NAT "){
			var args = getQueryStringArgs(data);
			if(args["users"] != null){
				$('ul').html('');
				var userStr = Trim(args["users"], true)
				var users = userStr.substr(1, userStr.lastIndexOf(']') - 1);
				$.each(users.split(','), function(index, user){
                    if(user !== username){
                        var u = $('<li class="item" data-user="'+user+'">' + user + '<span>Call</span></li>');
                        $('ul').append(u);
                    }
                });
			}
			if(args["play"] != null){
				var message = {};
				message.type = args["play"]
				switch(args["play"]){
				case "phonertc_handshake":
					if(args["data"] != null ){
						var splitStr = "&data=";
						var sdpData = data.substring(data.indexOf(splitStr)).split(splitStr)[1];
						message.data = sdpData;
					}
					if(args["data"] == ""){
						break;
					}
				case "start":
				case "answer":
				case "stop":
					onVideoMessageReceived(args["callingFrom"], message);
					break;
				default:
					break;
				}
			}
		}
	}
	
}